//
//  BaseViewController.swift
//  suda
//
//  Created by youai on 2019/7/11.
//  Copyright © 2019年 youi. All rights reserved.
//

import Foundation
import UIKit

class BaseViewController : UIViewController {
    init() {
        super.init(nibName: nil, bundle: nil)
        if #available(iOS 11.0, *) {
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    static var safeEdgeInsets : UIEdgeInsets? = nil
    func getSafeArea()->UIEdgeInsets{
        if BaseViewController.safeEdgeInsets != nil {
            return BaseViewController.safeEdgeInsets!
        }
        if #available(iOS 11.0, *) {
            if let nc = self.navigationController {
                BaseViewController.safeEdgeInsets = nc.view.safeAreaInsets
            }else{
                BaseViewController.safeEdgeInsets = self.view!.safeAreaInsets
            }
        } else {
            BaseViewController.safeEdgeInsets = UIEdgeInsets(top: 20,
                                                             left: 0,
                                                             bottom: 0,
                                                             right: 0)
        }
        return BaseViewController.safeEdgeInsets!
    }
    
    @objc lazy var safeView:UIView = {
        
        //先按375重置view的位置
        var screenSize = UIScreen.main.bounds.size
        if self.navigationController?.tabBarItem.title != nil || self.tabBarItem.title != nil{
            screenSize.height -= 49.0
        }
        var frame0 = view.frame
        let scale = screenSize.width / 375
        frame0.size.width = 375
        frame0.size.height = screenSize.height / scale
        view.frame = frame0
        view.layer.anchorPoint = .zero
        view.center = .zero
        view.transform = CGAffineTransform.identity.scaledBy(x: scale, y: scale)
        
        var s = getSafeArea()
//        s.left = s.left / scale
//        s.right = s.right / scale
//        s.top = s.top / scale
//        s.bottom = s.bottom / scale
//        let bottomOffset : CGFloat
//        if #available(iOS 11.0, *) { //在tabBar里面，在safeAreaInsets生效的版本，直接取底部
//            if self.navigationController?.tabBarItem.title != nil || self.tabBarItem.title != nil{
//                bottomOffset = 0
//            }else{
//                bottomOffset = -s.bottom
//            }
//        }else{
//            bottomOffset = -s.bottom
//        }
//        print(s.bottom)
        let margin : CGFloat = 0
        let viewSize = view.frame.size
        let frame = CGRect(
                origin: .init(x:margin,y:s.top+margin),
                size: .init(width:375-margin-margin ,
                            height:(viewSize.height)/scale-s.top-s.bottom-margin-margin))
        let areaView = ViewCopyBackgroundColor(frame: frame,targetView: self.view)
        self.view.addSubview(areaView)
//        areaView.clipsToBounds = true
        return areaView
    }()
    
    
    func switchViewController(vc:UIViewController){
        if let nav = self.navigationController ?? self.tabBarController?.navigationController,nav.viewControllers.count>0 {
            var vcs = nav.viewControllers
            vcs[vcs.count-1] = vc
            nav.setViewControllers(vcs, animated: true)
        }
    }
    
    //默认状态栏是白色字主题
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: 键盘支持
extension BaseViewController {
    
    ///让当前viewController可以监听键盘事件
    func initKeyboardObserver(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
    }
    
    ///为当前viewController的所有输入控件设置键盘上的完成按钮
    func fillAccessoryToolBar(target:UIView? = nil){
        let r = target == nil ? safeView : target!
        func _fillAccessoryToolBar(_ v:UIView) {
            if v.isKind(of: UITextField.self) {
                let textField = v as! UITextField
                if textField.delegate == nil {
                    textField.delegate = DefaultTextFieldDelegate.shared
                }
//                if (textField.returnKeyType != .done || textField.keyboardType != .default) && textField.inputAccessoryView == nil {
                if textField.inputAccessoryView == nil {
                    textField.inputAccessoryView = createAccessoryToolBar()
                }
            }else if v.isKind(of: UITextView.self) {
                let textView = v as! UITextView
                if textView.inputAccessoryView == nil {
                    textView.inputAccessoryView = createAccessoryToolBar()
                }
            }
            for subv in v.subviews {
                _fillAccessoryToolBar(subv)
            }
        }
        _fillAccessoryToolBar(r)
    }

    static func createAccessoryToolBar(target:NSObject,action:Selector)->UIToolbar{
        let accessoryDoneButton: UIBarButtonItem!
        let accessoryToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 44))
        accessoryDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: target, action: action)
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        accessoryToolBar.items = [flexibleSpace,accessoryDoneButton]
        return accessoryToolBar
    }
    
    func createAccessoryToolBar()->UIToolbar{
        return BaseViewController.createAccessoryToolBar(target: self, action: #selector(accessoryToolBarDonePressed))
    }
    
    @objc func accessoryToolBarDonePressed() {
        //Causes the view (or one of its embedded text fields) to resign the first responder status.
        view.endEditing(true)
    }
    
    func checkFirstResponder()->UIView?{
        func _check(target:UIView)->UIView? {
            if target.isFirstResponder {
                if target.isKind(of: UITextField.self) {
                    return target
                }else if target.isKind(of: UITextView.self) {
                    return target
                }
            }
            for view in target.subviews {
                let result = _check(target: view)
                if result != nil {
                    return result
                }
            }
            return nil
        }
        return _check(target: self.safeView)
    }
    
    @objc func keyboardWillHide(notification: NSNotification) {
        if let nav = navigationController {
            if (nav.visibleViewController != self)&&(nav.visibleViewController != self.tabBarController ) {
                return
            }
        }
        if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y = 0
        }
    }
    
    @objc func keyboardWillChange(notification: NSNotification) {
        if let nav = navigationController {
            if (nav.visibleViewController != self)&&(nav.visibleViewController != self.tabBarController ) {
                return
            }else{
                
            }
        }
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let target = checkFirstResponder()
            //            print(textField)
            if target != nil {
                let bottomPoint = CGPoint(x:0,y: target!.frame.maxY)
                let container = UIApplication.shared.keyWindow!
                let bottomPosition = container.convert(bottomPoint, from: target!).y
                var space = keyboardSize.height - (container.bounds.height - bottomPosition)
                
                if target?.isKind(of: UITextField.self) ?? false  {
                    space += (target as! UITextField).inputAccessoryView?.frame.size.height ?? 0
                }

                if target?.isKind(of: UITextView.self) ?? false {
                    space += (target as! UITextView).inputAccessoryView?.frame.size.height ?? 0
                }
  
                if self.view.frame.origin.y > -space {
                    self.view.frame.origin.y = -space
                }
            }
        }
    }
}

//自动收起键盘
class DefaultTextFieldDelegate : NSObject,UITextFieldDelegate{
    static let shared = DefaultTextFieldDelegate()
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}


class ViewCopyBackgroundColor : UIView {
    weak var targetView : UIView?
    init(frame: CGRect,targetView : UIView) {
        self.targetView = targetView
        super.init(frame: frame)
    }
    
    override var backgroundColor: UIColor? {
        get {return super.backgroundColor}
        set {
            super.backgroundColor = newValue
            targetView?.backgroundColor = newValue
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
